package com.neu.api.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.api.mapper.SchoolMapper;
import com.neu.api.entity.School;
import com.neu.api.query.SchoolQuery;
import com.neu.api.service.SchoolService;
import com.neu.api.utils.PageResult;
import com.neu.api.vo.SchoolVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class SchoolServiceImpl implements SchoolService {

    @Override
    public PageResult<SchoolVO> find(SchoolQuery SchoolQuery) {
        //设置是否需要分页
        PageHelper.startPage(SchoolQuery.getPage(), SchoolQuery.getPageSize());  //告诉PageHelper此处需要分页

        Page<SchoolVO> page = (Page<SchoolVO>) schoolMapper.find(SchoolQuery);

        PageInfo<SchoolVO> pageInfo = page.toPageInfo();


        List<SchoolVO> SchoolVOList = pageInfo.getList();
        long total = pageInfo.getTotal();

        PageResult<SchoolVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setList(SchoolVOList);

        return pageResult;
    }

    @Override
    public boolean udpateStatus(Integer id, Integer status) {
        return schoolMapper.updateStatus(id,status);
    }


    @Value("${neu.password}")
    private String password;

    @Value("${neu.salt}")
    private String salt;

    @Autowired
    SchoolMapper schoolMapper;

    @Override
    public boolean addSchool(SchoolVO schoolVO) {
//        School school = new school();
//        String password =
        String newPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes()); //MD5
        School school = new School();
        BeanUtils.copyProperties(schoolVO, school);
//        school.setAddress(schoolVO.getAddress());
//        school.


        school.setPassword(newPassword);

        System.out.println("school________________________ "+school.toString());

        schoolMapper.addSchool(school);


        return true;
    }

    @Override
    public boolean updateSchool(School user) {
        schoolMapper.updateSchool(user);
        return true;
    }

    @Override
    public boolean deleteSchool(int id) {
        schoolMapper.deleteSchool(id);
        return true;
    }

    @Override
    public School findSchoolById(String schoolName) {
        return schoolMapper.findById(schoolName);
    }

    @Override
    public List<School> findAll() {
        return schoolMapper.findAll();
    }


    @Override
    public School Login(String loginName, String password){
        password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        return schoolMapper.login(loginName, password);
    }
}
